const cloud = require('wx-server-sdk')
cloud.init({env: 'evn-cloud-a-4gf1q6iy9df62d73'})
const db = cloud.database()
const _ = db.command

const numberFormat = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
const dateFormatter = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const dateStr = `${[year, month, day].map(numberFormat).join('-')}`
  return dateStr
}

const updateMeritsVirtuesById = async (event) => {
  const _id = event._id
  const merit = event.meritsVirtues
  const currentDate = await dateFormatter(new Date())
  console.log('接受参数_id: ',_id,'merits: ',merit)
  if(_id == undefined || merit == undefined){
    console.error('id和功德主名(merit)都不能为空.')
    return {code: 20001,errMsg: 'ID和名称不能为空.'}
  }
  const transaction = await db.startTransaction()
  const queryKindPerResult = await transaction.collection('kindPersonList').doc(_id).get()
  console.log('查询功德主明细标结果为：',queryKindPerResult)
  const queryFreeCapResult = await transaction.collection('freeCaptiveDetails').where({meritsVirtues: queryKindPerResult.data.meritsVirtues, freeDate: currentDate}).limit(1).get()
  console.log('查询放生明细表结果为：',queryFreeCapResult)
  //放生明细表不为空则更新功德主名称
  if(queryFreeCapResult.data != undefined && queryFreeCapResult.data.length >= 0){
    const updateFreeCapResult = await transaction.collection('freeCaptiveDetails').doc(queryFreeCapResult.data[0]._id).update({data: {meritsVirtues: merit}})
    console.log('更新放生明细表结果为：',updateFreeCapResult)
    if(updateFreeCapResult.stats.updated != 1){
      await transaction.rollback()
      console.error('更新放生明细表失败，回滚事物.')
      return {code: 2001, errMsg: '更新失败.'}
    }
  }
  const updateResult = await transaction.collection('kindPersonList').doc(_id).update({data: { meritsVirtues: merit }})
  console.log('更新功德主表结果为：',updateResult)
  if(updateResult.stats.updated != 1){
    await transaction.rollback()
    console.error('更新善主明细表失败，回滚事物.')
    return {code: 2002, errMsg: '更新失败'}
  }
  await transaction.commit()
  console.log('更新成功，提交事务。')
  return {code: 0000, errMsg: '更新成功.'}
}
const deleteById = async (event) => {
  const _id = event._id
  const transaction = await db.startTransaction()
  const queryResult = await transaction.collection('kindPersonList').doc(_id).get()
  console.log('查询功德主列表结果为：',queryResult)
  const merit = queryResult.data.meritsVirtues
  const curDate = await dateFormatter(new Date())
  const queryFreeCapResult = await transaction.collection('freeCaptiveDetails').where({meritsVirtues: merit, freeDate: curDate }).limit(1).get();
  console.log('查询放生明细表结果为：',queryFreeCapResult)
  //如果当前功德主在放生明细表中存在当天信息，如果放生额和金额都为0，则可以删除，否则不能删除
  if(queryFreeCapResult.data != undefined && queryFreeCapResult.data.length == 1){
    const item = queryFreeCapResult.data[0]
    //如果放生额和余额都为0则删除，否则无法删除，
    if((item.freeAmount === "0" || item.freeAmount === '0.00') && (item.balance == '0' || item.balance === '0.00')){
      console.info('放生明细表中放生额和余额都为0，开始删除.')
      const deleteFreeDetResult = await transaction.collection('freeCaptiveDetails').where({meritsVirtues: merit, freeDate: curDate }).remove()
      console.info('删除放生明细表的结果为：',deleteFreeDetResult)
      if(deleteFreeDetResult.stats.removed != 1){
        await transaction.rollback()
        console.error('删除失败，事物开始回滚.')
        return {code: 2001, errMsg: '删除失败.'}
      }
    }else{
      await transaction.rollback()
      console.error('删除失败，放生额和余额都为0才能删除，但此不都为0，事物开始回滚.')
      return {code: 2002, errMsg: '金额不为零无法删除.'}
    }
  }
  const deleteKindPerLisResult = await transaction.collection('kindPersonList').doc(_id).remove()
  console.log('删除当日功德主明细表为：',deleteKindPerLisResult)
  if(deleteKindPerLisResult.stats.removed != 1){
    await transaction.rollback()
    console.error('删除失败，事物开始回滚.')
    return {code: 2001, errMsg: '删除失败.'}
  }
  await transaction.commit()
  console.info('事物已提交，操作成功.')
  return { code: 0000, errMsg: '操作成功.'}
}
//添加功德主名称时，顺便生成当日放生明细
const addInfo = async (event) => {
  const merit = event.meritsVirtues
  if(merit==''|| merit == undefined){
    console.error('功德主名（meritsVirtues）不能为空.')
    return {data: undefined, errMsg: '功德主名不能为空'}
  }
  const queryResult = await db.collection('kindPersonList').where({meritsVirtues: merit}).get({})
  console.log('查询结果为：',queryResult)
  if(queryResult.data != undefined && queryResult.data.length > 0){
    console.error('功德主名已存在，不能重复添加.')
    return {data: undefined, errMsg: '功德主名已存在，不能重复添加.'}
  }

  const transaction = await db.startTransaction()
  const addPeListResult = await transaction.collection('kindPersonList').add({data: {meritsVirtues: merit}})
  console.log('新增功德主结果为：',addPeListResult)

  const currDate = await dateFormatter(new Date())
  const queryFreeCapResult = await transaction.collection('freeCaptiveDetails').where({freeDate: currDate, meritsVirtues: merit}).get()
  console.log('查询放生明细表(freeCaptiveDetails)结果为：', queryFreeCapResult)
  if(queryFreeCapResult.data != null && queryFreeCapResult.data.length > 0 ){
    console.error('放生明细表(freeCaptiveDetails)中已存在此数据,事物回滚.')
    await transaction.rollback()
    return {data: undefined, errMsg: '数据已存在.'}
  }
  const addFreeCapDetResult = await transaction.collection('freeCaptiveDetails').add({data: { meritsVirtues: merit, freeDate: currDate, freeAmount: '0', balance: 0, chargeAmount: 0, isSelect: false }})
  console.log('新增放生明细结果为：', addFreeCapDetResult)
  if(addFreeCapDetResult._id == undefined || addFreeCapDetResult._id == '' || addPeListResult._id == undefined || addPeListResult._id == ''){
    console.error('添加失败，事物回滚.')
    await transaction.rollback()
    return {data: undefined, errMsg: '添加失败'}
  }
  await transaction.commit()
  console.log('事物提交成功，开始返回.','\n\n')
  return addPeListResult
}
const main= async(event) => {
  const reqType = event.reqType
  switch(reqType){
    case 'addInfo':
      return await addInfo(event)
    case 'updatedMeritById':
      return await updateMeritsVirtuesById(event)
    case 'deleteById':
      return await deleteById(event)
    default:
      console.error('请求类型不存在.')  
  }
}

module.exports = {
  main
}
